require("dotenv").config();

const express = require("express");
const morgan = require("morgan");
const helmet = require("helmet");
const cors = require("cors");
const compression = require("compression");
const path = require("path");
const { notFound, errorHandler } = require("./middleware/error");

const app = express();

// —— 基础安全 ——
// 设置常见安全头
app.use(helmet());

// CORS
app.use(cors({
    origin: process.env.CORS_ORIGIN?.split(",") || "*",
    credentials: true,
}));

// Gzip 压缩
app.use(compression());

// 日志
app.use(morgan(process.env.NODE_ENV === "production" ? "combined" : "dev"));

// 解析 JSON 和表单
app.use(express.json({ limit: "1mb" }));
app.use(express.urlencoded({ extended: true }));

// 静态资源：上传目录
app.use("/uploads", express.static(path.join(process.cwd(), "uploads")));

// 路由
app.use("/api", require("./routes"));

// 404 与错误处理
app.use(notFound);
app.use(errorHandler);

module.exports = app;
